const Router = require("@koa/router");
const { Pool } = require("pg");
const router = new Router({ prefix: "/ski-logs" });
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 上传日志接口
router.post("/", async (ctx) => {
  try {
    const { user_id, app_version, ios_version, level, message, timestamp } = ctx.request.body;

    if (message.includes("未找到存储的个人信息")){
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "排除异常信息"
      };
      return;
    }
    
    // 验证必填字段
    if (!user_id || !level || !message) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "缺少必填字段：user_id, level, message"
      };
      return;
    }
    
    // 检查是否与上一条日志重复
    const lastLogResult = await pool.query(
      "SELECT user_id, app_version, ios_version, level, message FROM ski_logs WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1",
      [user_id]
    );
    
    if (lastLogResult.rows.length > 0) {
      const lastLog = lastLogResult.rows[0];
      if (lastLog.user_id === user_id && 
          lastLog.app_version === app_version && 
          lastLog.ios_version === ios_version && 
          lastLog.level === level && 
          lastLog.message === message) {
        ctx.status = 444;
        ctx.body = {
          success: false,
          message: "重复的日志内容，已忽略"
        };
        return;
      }
    }
    
    // 插入日志到数据库
    // 处理timestamp，加8小时
    let adjustedTimestamp;
    if (timestamp) {
      const originalDate = new Date(timestamp);
      adjustedTimestamp = new Date(originalDate.getTime() + 8 * 60 * 60 * 1000);
    } else {
      adjustedTimestamp = new Date();
    }
    
    const result = await pool.query(
      "INSERT INTO ski_logs (user_id, app_version, ios_version, level, message, timestamp) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
      [user_id, app_version, ios_version, level, message, adjustedTimestamp]
    );
    
    console.log(`${new Date().toLocaleString()} 日志已保存:`, {
      id: result.rows[0].id,
      user_id,
      level,
      message: message.substring(0, 100) + (message.length > 100 ? '...' : '')
    });
    
    ctx.body = {
      success: true,
      message: "日志上传成功",
      data: {
        id: result.rows[0].id,
        created_at: result.rows[0].created_at
      }
    };
    
  } catch (err) {
    console.error(`${new Date().toLocaleString()} 日志上传失败:`, err);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "服务器内部错误"
    };
  }
});

// 查询日志列表接口（支持分页）
router.get("/", async (ctx) => {
  try {
    // 获取查询参数
    const {
      page = 1,
      page_size = 10,
      user_id,
      level,
      start_date,
      end_date
    } = ctx.query;
    
    // 验证分页参数
    const pageNum = parseInt(page);
    const pageSize = parseInt(page_size);
    
    if (pageNum < 1 || pageSize < 1 || pageSize > 100) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "分页参数无效：页码必须大于0，每页数量必须在1-100之间"
      };
      return;
    }
    
    // 构建查询条件和参数
    let whereConditions = [];
    let queryParams = [];
    let paramIndex = 1;
    
    if (user_id) {
      whereConditions.push(`user_id = $${paramIndex}`);
      queryParams.push(user_id);
      paramIndex++;
    }
    
    if (level) {
      whereConditions.push(`level = $${paramIndex}`);
      queryParams.push(level);
      paramIndex++;
    }
    
    if (start_date) {
      whereConditions.push(`created_at >= $${paramIndex}`);
      queryParams.push(start_date);
      paramIndex++;
    }
    
    if (end_date) {
      whereConditions.push(`created_at <= $${paramIndex}`);
      queryParams.push(end_date);
      paramIndex++;
    }
    
    const whereClause = whereConditions.length > 0
      ? `WHERE ${whereConditions.join(' AND ')}`
      : '';
    
    // 计算偏移量
    const offset = (pageNum - 1) * pageSize;
    
    // 查询总记录数
    const countQuery = `SELECT COUNT(*) FROM ski_logs ${whereClause}`;
    const countResult = await pool.query(countQuery, queryParams);
    const totalCount = parseInt(countResult.rows[0].count);
    
    // 查询分页数据
    queryParams.push(pageSize, offset);
    const dataQuery = `
      SELECT
        id, user_id, app_version, ios_version, level, message,
        timestamp, created_at
      FROM ski_logs
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT $${paramIndex} OFFSET $${paramIndex + 1}
    `;
    
    const dataResult = await pool.query(dataQuery, queryParams);
    
    // 计算总页数
    const totalPages = Math.ceil(totalCount / pageSize);
    
    ctx.body = {
      success: true,
      data: {
        items: dataResult.rows,
        pagination: {
          current_page: pageNum,
          page_size: pageSize,
          total_count: totalCount,
          total_pages: totalPages,
          has_next: pageNum < totalPages,
          has_prev: pageNum > 1
        }
      }
    };
    
  } catch (err) {
    console.error(`${new Date().toLocaleString()} 日志查询失败:`, err);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: "服务器内部错误"
    };
  }
});

module.exports = router;